import cv2

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('train_data.yml')   # 读取已经训练好的数据集
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
idnum = 0
subjects = ['Zhou Xinchi', 'Peng Yuyan', 'Cheng Long']   # 人脸数据集标签
threshold = 60
while 1:
    ret, frame = cap.read()
    imag = frame.copy()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
    for (x, y, w, h) in faces:
        cv2.rectangle(imag, (x, y), (x + w, y + h), (0, 255, 0), 2)
        idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])
        print('idnum:', idnum)
        print('confidence:', confidence)
        if 100 > confidence > threshold:
            idnum = subjects[idnum]
            cv2.putText(imag, str(idnum), (x + 5, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        else:
            idnum = "unknown"
            cv2.putText(imag, idnum, (x + 5, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow('camera', imag)
    k = cv2.waitKey(1)
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
